﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.IO;

namespace AGuang.WebTool {
    public class NetworkStreamProcess {
        /// <summary>
        /// 获取网络文件（http）,转换为内存流
        /// </summary>
        /// <param name="uri"></param>
        /// <returns></returns>
        public Stream GetNetworkFile(Uri uri) {
            int realReadCount;
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
            request.Referer = uri.ToString();
            request.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 2.0.50727)";
            request.Accept = "image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-shockwave-flash, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*";
            WebResponse response = request.GetResponse();
            Stream responseStream = response.GetResponseStream();
            Stream networkBufferStream = new BufferedStream(responseStream);
            Stream memoryBufferStream = new BufferedStream(new MemoryStream());
            
            int count = 0x1000;
            byte[] buffer = new byte[count];//一次性读取的字节数
            while ((realReadCount = networkBufferStream.Read(buffer, 0, count)) > 0) {
                memoryBufferStream.Write(buffer, 0, realReadCount);
            }
            responseStream.Close();
            networkBufferStream.Close();
            response.Close();
            memoryBufferStream.Position = 0L;
            return memoryBufferStream;
        }

        /// <summary>
        /// 向web上传文件
        /// </summary>
        /// <param name="stream">必须为可获取长度的本地流</param>
        /// <param name="fieldName">表单名</param>
        /// <param name="filename">用于表示的文件名</param>
        /// <param name="uploadUri"></param>
        /// <returns></returns>
        public string UploadData(Stream stream,String fieldName, string filename, Uri uploadUri) {
            int realReadCount;
            string str = "---------------------------" + DateTime.Now.Ticks.ToString("x");
            string s = string.Format("--{0}\r\nContent-Disposition: form-data; name=\"{1}\"; filename=\"{2}\"\r\nContent-Type: application/octet-stream\r\n\r\n", str, fieldName, filename);//头
            byte[] startBytes = Encoding.ASCII.GetBytes(s);
            string e = string.Format("\r\n--{0}--\r\n", str);//尾
            byte[] endBytes = Encoding.ASCII.GetBytes(e);

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uploadUri);
            request.Method = "POST";
            request.AllowWriteStreamBuffering = false;
            request.ContentLength = (startBytes.LongLength + stream.Length) + endBytes.LongLength;
            request.ContentType = "multipart/form-data; boundary=" + str;
            Stream requestStream = request.GetRequestStream();
            
            requestStream.Write(startBytes, 0, startBytes.Length);
            int count = 0x1000;//一次性读取的字节数
            byte[] buffer = new byte[count];
            while ((realReadCount = stream.Read(buffer, 0, count)) > 0) {
                requestStream.Write(buffer, 0, realReadCount);
            }
            requestStream.Write(endBytes, 0, endBytes.Length);
            
            StreamReader reader = null;
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream responseStream = response.GetResponseStream();
            if (string.IsNullOrEmpty(response.CharacterSet)) {
                reader = new StreamReader(responseStream);
            } else {
                reader = new StreamReader(responseStream, Encoding.GetEncoding(response.CharacterSet));
            }
            string backStr = reader.ReadToEnd();
            requestStream.Close();
            responseStream.Close();
            response.Close();
            return backStr;
        }
    }
}

